# -*- coding:utf-8 -*-
"""
图像
"""
from random import random
import logging
from datetime import datetime

import numpy as np

import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure


from LibrarySystem.config.config import Config

mpl.use('Qt5Agg')
plt.rcParams['font.sans-serif'] = ['SimHei']

module_logger = logging.getLogger("logger.sub")


class CustomFigure(FigureCanvas):
    """
    @ClassName：CustomFigure
    @Description：CustomFigure 映射一个统计图表，可以存在多个
    负责统计页面里的图表绘制，初始化时接收 图像名称
    @Author：锦沐Python
    """

    def __init__(self, name):
        self.fig = Figure(figsize=(6, 6))
        super().__init__(self.fig)
        self.name = name
        self.axes = self.fig.add_subplot(111)
        self.config = Config()

    def create_scatter(self, x, y, title, x_label="", y_label=""):
        module_logger.info("开始创建散点图")
        self.axes.clear()
        self.axes.scatter(x, y, color='b')

        # 在点的旁边添加坐标值的注释
        for i, txt in enumerate(x):
            self.axes.annotate(txt, (x[i], y[i]), textcoords="offset points",
                               xytext=(7, -5), rotation=90, ha='center', va='center')

            self.axes.annotate(y[i], (x[i], y[i]), textcoords="offset points",
                               xytext=(-10, 15), rotation=90, ha='center', va='center')

        # 隐藏实际横坐标刻度
        self.axes.set_xticks([])
        self.axes.set_yticks([])
        self.axes.set_ylim(-1, len(y) + 1)
        self.axes.set_xlim(-1, len(x))
        self.axes.set_title(title)
        self.axes.set_xlabel(x_label)
        self.axes.set_ylabel(y_label)

        self.fig.canvas.draw()
        module_logger.info("刷新画布")

    def create_bar(self, x, y, title, x_label="", y_label=""):
        module_logger.info("开始创建柱状图")
        self.axes.clear()
        bars = self.axes.bar(x, y)

        for bar, label in zip(bars, y):
            bar.set_color(self._generate_random_color())
            height = bar.get_height()
            self.axes.text(bar.get_x() + bar.get_width() / 2, height / 2, label,
                           ha='center', va='center', rotation=90, color='w')

        self.axes.set_yticks([])
        self.axes.set_title(title)
        self.axes.set_xlabel(x_label)
        self.axes.set_ylabel(y_label)

        self.fig.canvas.draw()
        module_logger.info("刷新画布")

    def create_pie(self, x, y, title, x_label="", y_label=""):
        module_logger.info("开始创建饼图")
        self.axes.clear()
        self.axes.pie(x, labels=y, autopct='%6.1f%%')

        self.axes.set_title(title)
        self.axes.set_xlabel(x_label)
        self.axes.set_ylabel(y_label)

        self.fig.canvas.draw()
        module_logger.info("刷新画布")

    def create_clould(self, words, title, x_label="", y_label=""):
        # 使用散点图实现简单的词云
        module_logger.info("开始创建词云图")
        self.axes.clear()
        num_words = min(len(words), 40)
        _x = np.random.rand(num_words)
        _y = np.random.rand(num_words)

        # 随机生成字体大小
        sizes = np.random.randint(8, 30, num_words)

        # 随机生成颜色
        plt_colors = [self._generate_random_color() for _ in range(num_words)]

        for i in range(num_words):
            self.axes.text(_x[i], _y[i], words[i], fontsize=sizes[i], color=plt_colors[i], ha='center', va='center')

        # 关闭坐标轴
        self.axes.axis('off')
        self.axes.set_title(title)
        self.axes.set_xlabel(x_label)
        self.axes.set_ylabel(y_label)

        self.fig.canvas.draw()
        module_logger.info("刷新画布")

    def graph_out(self):
        """
        导出图像
        @return:
        """
        try:
            self.fig.savefig(fname=self.config.STATS_IMG_SAVE_PATH + f"\\{str(self.name)}-{datetime.now().strftime('%H-%M-%S')}.png", dpi=250)

            module_logger.info(f"{self.name}图像导出至:{self.config.STATS_IMG_SAVE_PATH}")

        except Exception as e:
            module_logger.error(f"{self.name}图像导出错误:{e}")

    def _generate_random_color(self):
        r = random()
        g = random()
        b = random()
        return (r, g, b)

    def clear(self):
        self.axes.clear()
        self.fig.canvas.draw()
